/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SecretSanta.service.impl;

import SecretSanta.service.MailClient;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Mallisa
 */
public class MailClientImpl implements MailClient {
    private String SMTP_HOST;
    private String SMTP_SOCKETFACTORY_PORT;
    private String SMTP_SOCKETFACTORY_CLASS;
    private String SMTP_AUTH;
    private String SMTP_PORT;
	
    private String CLIENT_EMAIL;
    private String CLIENT_PASSWORD;
	
    private String PROPPATH = "src/resources/config.properties";
    private Properties prop;
    
    /**
     * @param args
     */
    public static void main(String[] args) {
	MailClient client = new MailClientImpl();
//	System.out.println("Sending Email");
//	client.send("randellma@gmail.com", "Matthew", "Mallisa", 2011);
	System.out.println("Sending Email");
	client.send("mallisale@gmail.com", "Mallisa", "Matthew", 2011);	
    }
	
    public MailClientImpl() {
	//Initialize the SMTP host information
	SMTP_HOST = getProperty("SMTP_HOST");
	SMTP_SOCKETFACTORY_PORT = getProperty("SMTP_SOCKETFACTORY_PORT");
	SMTP_SOCKETFACTORY_CLASS = getProperty("SMTP_SOCKETFACTORY_CLASS");
	SMTP_AUTH = getProperty("SMTP_AUTH");
	SMTP_PORT = getProperty("SMTP_PORT");
		
	CLIENT_EMAIL = getProperty("CLIENT_EMAIL");
	CLIENT_PASSWORD = getProperty("CLIENT_PASSWORD");
    }
    
    /**
     * Retrieves message from config.properties, inputs parameters into message and e-mails
     * to all participants of the Secret Santa
     * @param recipient_email   (String) Email address of the Secret Santa
     * @param recipient_name    (String) Name of the Secret Santa
     * @param secret_name       (String) Name of the recipient of Secret Santa's gift
     * @param year              (int) Year that the secret name was assigned
     * @return true if email sent successfully, else false
     */
    public boolean send (String recipient_email, String recipient_name, String secret_name, int year) {
        try {
            //Set host SMTP address
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST);
            props.put("mail.smtp.socketFactory.port", SMTP_SOCKETFACTORY_PORT);
            props.put("mail.smtp.socketFactory.class", SMTP_SOCKETFACTORY_CLASS);
            props.put("mail.smtp.auth", SMTP_AUTH);
            props.put("mail.smtp.port", SMTP_PORT);
		
            //Get the session and input properties
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(CLIENT_EMAIL, CLIENT_PASSWORD);
                }
            });
            session.setDebug(false);
			
            //Create message
            Message msg = new MimeMessage(session);	
            String body = getProperty("message_body");
            body = body.replace("[$recipient]", recipient_name);
            body = body.replace("[$secret]", secret_name);
            body = body.replace("[$year]", Integer.toString(year));
			
            //Send message
            InternetAddress addressFrom = new InternetAddress(CLIENT_EMAIL);
            InternetAddress addressTo = new InternetAddress(recipient_email);
            msg.setFrom(addressFrom);
            msg.setRecipient(Message.RecipientType.TO, addressTo);
            msg.setSubject("Secret Santa!!");
            msg.setContent(body, "text/html");
		
            Transport.send(msg);
            System.out.println("Complete");
            return true;
	} catch (MessagingException me) {
            System.out.println("Error: " + me.getMessage());
            me.printStackTrace();
            return false;
	}        
    }
    
    private String getProperty(String key) {
	if (prop == null) {
            prop = new Properties();
            try {
            	prop.load(new FileInputStream(PROPPATH));
            } catch (IOException e) {
                System.out.println("[Error] " + e.getMessage());
            }
	}
	return prop.getProperty(key);
    }
    
}